students = []
cs = ""
s = []
#how much time have this course
times = 0
sd = []
tmpCheck = 0
time_each = new Date()
#del students
dstudents = []
openClass = []

loading = $ 'div.loading'

$ document
	.ready ()->
		if ($.cookie "dstudents")?
			dstudents = $.cookie("dstudents").split(",")
		getStudent(afterGet)
		$ ".quikCheck#tmp"
			.bind 'click',()->
				tmpCheck = 1
				$ ".log"
					.text "请输入封面激活码"
				$ ".mask"
					.css "display","block"
		$ "button#sure"
			.bind 'click',ts
		$ "button#reset"
			.bind 'click',()->
				window.open "/key/#{cid}.xlsx"
		$ "button.cancle"
			.bind 'click',()->
				$ ".mask"
					.css 'display','none'
		$ ".qr"
			.qrcode "text":"http://signup.misasagi.me/student/addCourse/#{cid}","height":100,"width":100

$ document
	.keydown (event)->
		if event.keyCode is 27
			$ ".mask"
				.css 'display','none'

afterGet = ()->
	$ ".courseList"
		.bind 'click',()->
			list = $ @
				.find ".studentList"
			comment = $ @
				.find ".courseHead"
				.find ".comment"
			if list.css("display") is "block"
				list.css "display","none"
				comment.css "display","none"
				if ($.inArray $(@).attr("id"),openClass) isnt -1
					openClass.splice ($.inArray $(@).attr("id"),openClass),1
			else
				list.css "display","block"
				comment.css "display","block"
				console.log $(@).attr("id")
				openClass.push $(@).attr("id")
				console.log openClass
	$ "input.cb"
		.bind 'click',(e)->
			e.stopPropagation()
			if ($.cookie 'dstudents')?
				dstudents = ($.cookie 'dstudents').split ','
			if @.checked
				if ($.inArray @.id,dstudents) is -1
					dstudents.push @.id
			else
				dstudents.splice ($.inArray @.id,dstudents),1
			now = new Date()
			$.cookie 'dstudents',dstudents.join(','),{expires: 365 ,path:"/teacher/course/#{cid}"}
			classStudent()
			afterGet()
	cs = ""
	s = []
	loading.css 'display','none'

ts = ()->
	loading.css 'display','block'
	if tmpCheck == 0
		number = $ 'input[name=key]'
			.val()
		$.post "/teacher/course/#{cid}/signup",'number':number,(data)->
			if data.head is 'ok'
				window.open "/key/#{cid}_#{times+1}.pdf"
				$ ".log"
					.text "申请激活码成功"
				getStudent(afterGet)
			else
				$ ".log"
					.text data.info
	else
		tmp = $ 'input[name=key]'
			.val()
		$.post "/teacher/course/#{cid}/binding",'code':tmp,(data)->
			if data.head is 'ok'
				$ ".log"
					.text "绑定成功"
				$ '.mask'
					.css 'display','none'
				getStudent(afterGet)
			else
				$ ".log"
					.text data.info
	loading.css 'display','none'

getStudent = ()->
	students = []
	loading.css 'display','block'
	$.get '/teacher/course/student/' + cid,(data)->
		if err?
			$ '.log'
				.text 'error!please refresh this page'
		else
			if data.info[0]
				inStack student for student in data.info
				times = data.info[0].course.signup_times
				time_each = data.info[0].course.time_each
				classStudent()
			afterGet()

init_sd = ()->
		for _s in [1..times]
			sd[_s] = 0

#format students
inStack = (s)->
	sum = 'sid':s.student._id,'sname':s.student.sname,'sclass':s.student.sclass,'signup':s.signup
	students.push sum

#log and class students into there class
classStudent = (ele,cb)->
	loading.css 'display','block'
	$ ".courseList"
		.remove()
	students = iSort(students)
	s = []
	for index of students
		classes index
	if cb?
		setTimeout cb,300,ele

classes = (index)->
	if students[index].sclass !=  cs
		if cs isnt ''
			flushCourse cs
			cs = students[index].sclass
			s.push students[index]
			if index/1 is students.length-1
				flushCourse cs
		else if index/1 is students.length-1
			cs = students[index].sclass
			s.push students[index]
			flushCourse cs
		else
			cs = students[index].sclass
			s.push students[index]
	else if index/1 is students.length-1
		s.push students[index]
		flushCourse cs
	else
		s.push students[index]

#print a class
flushCourse = (cs)->
	s.sort (a,b)->
		if ($.inArray a.sid,dstudents) isnt -1 && ($.inArray b.sid,dstudents) isnt -1
			a.sid/1 - b.sid/1
		else if ($.inArray a.sid,dstudents) isnt -1
			1
		else if ($.inArray b.sid,dstudents) isnt -1
			-1
		else
			a.sid/1 - b.sid/1
	init_sd()
	if ($.inArray cs,openClass) isnt -1
		dis="block"
	else
		dis="none"
	list = $ "<div class=\"courseList\" id=\"#{cs}\"></div>"
	head = $ '<div class="courseHead"></div>'
		.html "<h1 class='courseTitle' > #{cs}</h1><h2 class='comment' style='display:#{dis}' ><font id='yes' >*注:p</font>代表到/<font id='no'>a</font>代表没到</h2>"
	studentList = $ "<div class='studentList' style='display:#{dis}'></div>"
	table = $ "<table ></table>"
	table.append genHead()
	table.append checkStudent s
	table.append countSigns()
	studentList.append table
	sd = []
	list.append head,studentList
	$ 'div.courseBody'
		.append list
	s = []

#print how much student signup for each time
countSigns = ()->
	count = "<tr ><td class='sid'> </td><td class='sname'>"
	n = 1
	while n <= times
		count += "<td>#{sd[n]}/#{s.length}</td>"
		n += 1
	count += "</tr>"
	return $ count

#gen the head for each class
genHead = ()->
	tr = $ "<tr></tr>"
	tr.append "<th class='sid'></th>"
	tr.append "<th class='sname'></th>"
	n = 1
	while n <= times
		th = $ "<th class='sign'></th>"
		th.html getTh n
		tr.append th
		n += 1
	tr

#get th module such as 1st,2ed...
getTh = (n)->
	for t in time_each
		if n is t.times
			console.log t
			day =  new Date(Date.parse(t.time.split("T")[0].replace(/-/g,"/")))
			return "#{day.getMonth() + 1}-#{day.getDate()}"
	switch n
		when 1 then  "1<sup>st</sup>"
		when 2 then  "2<sup>nd</sup>"
		when 3 then  "3<sup>rd</sup>"
		else  "#{n}<sup>th</sup>"

#check if the student had signed each course
checkStudent = (ss)->
	lines = []
	for stu in ss
		if ($.inArray stu.sid,dstudents) isnt -1
			line = $ "<tr><td class='sid'><input type='checkbox' class='cb' id=\"#{stu.sid}\" checked='checked'>#{stu.sid}</td><td class='sname'>#{stu.sname}</td></tr>"
		else
			line = $ "<tr><td class='sid'><input type='checkbox' class='cb' id=\"#{stu.sid}\">#{stu.sid}</td><td class='sname'>#{stu.sname}</td></tr>"
		n = 1
		while n<= times
			_s = signup n,stu.signup
			if _s is "p"
				line.append "<td class='sign' id='yes'>p</td>"
			else if _s is "i"
				line.append "<td class='sign' id='ill'>i</td>"
			else
				line.append "<td class='sign' id='no'>a</td>"
			n += 1
		lines.push line
	lines

signup = (time,st)->
	for n of st
		if st[n].time is time
			if st[n]._id is "000000000000"
				return "i"
			else
				sd[time] += 1
				return "p"
	return "a"
	
iSort = (array)->
	tem = []
	for i in [0..array.length-1]
		if i is 0
			tem[0] = array[i]
		else
			for j in [0..tem.length-1]
				if string20x(array[i].sclass) > string20x(tem[j].sclass)
					if j is tem.length-1
						tem[j+1] = array[i]
						break
					else
						continue
				else
					for k in [tem.length-1..j]
						tem[k+1] = tem[k]
					tem[j]=array[i]
					break
	tem

string20x = (str)->
	pf = str.substr 0,2
	gd = str.substr -4
	es = escape pf
	es = es.replace /%u/g,""
	x = "0x#{es}#{gd}"
	x/1

	


	

